package park.borne;


import park.borne.impl.ClavierImpl;
import mat.i2c.slave.PortException;

/**
 *
 * <p>Titre : Clavier</p>
 * <p>Description : un clavier de 16 touches</p>
 * <p>Copyright : Copyright (c) 2003</p>
 * <p>Société : </p>
 * @author Gilles Petot
 * @version 1.0
 */
public final class Clavier implements ScanListener
{
    private static final byte NBRETOUCHES    = (byte)16;
    private static final byte PASDAPPUI      = (byte)0xFF;
    private ClavierImpl clavierImpl;
    private byte codeGeoMem = PASDAPPUI;
    private boolean touchesRelachees = true; //memorisation de l'etat "touches relachees" pour valider un nouvel appui sur une touche
    private Borne borne = null;

    /**
     * constructeur
     */
    public Clavier(final Borne borne) throws PortException
    {
	this.borne = borne;
	clavierImpl = new ClavierImpl();
	clavierImpl.init();
    }


    private final void memoriseEvent(final byte codeGeo)
    {
	borne.putEvent((byte)codeGeo);
    }

    /**
     *  scrutation du clavier par un timer (ScanThread) toutes les 10ms
     *  les touches apuyees sont detectees ici et placees dans un petit tampon
     *  on effectue 2 lectures pour se premunir des rebonds eventuels
     */
     public final void doScan()
     {
	byte oldCodeGeo = codeGeoMem;
	byte codeGeo = clavierImpl.scan();
	codeGeoMem = (byte)codeGeo;
	if (codeGeo == oldCodeGeo)
	{
	    if(codeGeo != PASDAPPUI)                        // si touche appuyee
	    {
	       if (touchesRelachees)
	       {
		   byte codeTouche = clavierImpl.getCodeTouche(codeGeo);//byte)ValTouche((byte)codeGeo);
		   memoriseEvent((byte)codeTouche);
	       }
	       touchesRelachees = false;
	    }
	    else
	    {
		touchesRelachees = true;
	    }
	  }
     }

    public final void kill()
    {
       clavierImpl.kill();
       clavierImpl = null;
    }
}
